package controllers

import (
	"github.com/jinzhu/gorm"
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"tizhi_front/model"
	"tizhi_front/nspel"
	"tizhi_front/response"
	"tizhi_front/utils"
)

type ArticleController struct {
	Ctx iris.Context
}

func (c *ArticleController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/list/{Type:int}/{offset:int}", "GetArticleList", beforeCommonToken)
	b.Handle("POST", "/detail/{id:long}", "GetArticleDetail", beforeCommonToken)
	b.Handle("PUT", "/add_watch_count/{id:long}", "AddWatchCount", beforeCommonToken)
	b.Handle("POST", "/collect/{id:long}", "ArticleCollect", beforeCommonToken)
	b.Handle("POST", "/like/{id:long}", "ArticleLike", beforeCommonToken)
	b.Handle("POST", "/un_collect/{id:long}", "ArticleUnCollect", beforeCommonToken)
	b.Handle("POST", "/un_like/{id:long}", "ArticleUnLike", beforeCommonToken)
	b.Handle("POST", "/collect/list/{Type:int}/{offset:int}", "GetCollectArticleList", beforeCommonToken)
}

// @Title Article List
// @Description 根据类别获取知识视窗或者校园体育的文章列表
// @Tags article
// @Param	offset path int64	true "offset for list"
// @Param	type path int	true "type for article,0:运动处方 1:校园体育"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.ArticleList
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /article/list/{type}/{offset} [post]
func (c *ArticleController) GetArticleList(Type int, offset int) response.JsonResponse {
	article := model.ArticleE{}
	articles, err := article.SelectAllByTypeOrderByCreateAtDesc(byte(Type))
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.ArticleList{
		ShortShowCount:  3,
		PerRequestCount: 8,
		TotalCount:      int64(len(articles)),
		Offset:          int64(offset),
		ArticleList:     []response.ArticleListInfo{},
	}
	for i := offset; i < offset+8 && i < len(articles); i++ {
		res.ArticleList = append(res.ArticleList, response.ArticleListInfo{
			Id:           articles[i].Id,
			Type:         int(Type),
			VideoPic:     articles[i].VideoPic,
			ThumbnailUrl: articles[i].ThumbnailUrl,
			VideoKey:     articles[i].VideoKey,
			WatchCount:   articles[i].WatchCount,
			LikeCount:    articles[i].LikeCount,
			Title:        articles[i].Title,
			CreateTime:   articles[i].CreateAt.Format("2006-01-02 15:04:05"),
			Description:  articles[i].Description,
		})
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Article Detail
// @Description 根据Id获取文章详情
// @Tags article
// @Param	id path int64	true "id for article"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.ArticleDetailInfo
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /article/detail/{id} [post]
func (c *ArticleController) GetArticleDetail(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	article := model.Article1{}
	err = article.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.ArticleDetailInfo{
		Content: article.Content,
		ArticleListInfo: response.ArticleListInfo{
			Id:           article.Id,
			Type:         int(article.Type),
			ThumbnailUrl: article.ThumbnailUrl,
			VideoKey:     article.VideoKey,
			WatchCount:   article.WatchCount,
			LikeCount:    article.LikeCount,
			Title:        article.Title,
			CreateTime:   article.CreateAt.Format("2006-01-02 15:04:05"),
			Description:  article.Description,
		},
		RecommendArticles: []response.ArticleListInfo{},
	}
	articleLike := model.ArticleLikeE{}
	err = articleLike.SelectByStudentIdArticleId(uid, id)
	if err != nil && err != gorm.ErrRecordNotFound {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err != nil {
		err = nil
	} else {
		res.Like = true
	}
	count, err := articleLike.SelectCountByArticleId(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res.LikeCount = count
	articleCollect := model.ArticleCollectE{}
	err = articleCollect.SelectByStudentIdArticleId(uid, id)
	if err != nil && err != gorm.ErrRecordNotFound {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err != nil {
		err = nil
	} else {
		res.Collect = true
	}
	articleE := model.ArticleE{}
	articles, err := articleE.SelectAllByTypeOrderByWatchCountDesc(article.Type)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	for i := 0; len(res.RecommendArticles) < 3 && i < len(articles); i++ {
		if articles[i].Id == id {
			continue
		}
		count, err = articleLike.SelectCountByArticleId(articles[i].Id)
		if err != nil {
			nspel.Error(err)
			return response.JsonResponse{
				ErrCode: 2,
				ErrInfo: err.Error(),
				Data:    "",
			}
		}
		res.RecommendArticles = append(res.RecommendArticles, response.ArticleListInfo{
			Id:           articles[i].Id,
			Type:         int(article.Type),
			VideoPic:     articles[i].VideoPic,
			ThumbnailUrl: articles[i].ThumbnailUrl,
			VideoKey:     articles[i].VideoKey,
			WatchCount:   articles[i].WatchCount,
			LikeCount:    count,
			Title:        articles[i].Title,
			CreateTime:   articles[i].CreateAt.Format("2006-01-02 15:04:05"),
			Description:  articles[i].Description,
		})
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Article Watch Count Add
// @Description 根据Id,添加文章浏览次数
// @Tags article
// @Param	id path int64	true "id for article"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /article/add_watch_count/{id} [put]
func (c *ArticleController) AddWatchCount(id int64) response.JsonResponse {
	article := model.ArticleE{}
	watchCount, err := article.UpdateWatchCountAddById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    watchCount,
	}
}

// @Title Article Collect
// @Description 根据Id,添加到收藏
// @Tags article
// @Param	id path int64	true "id for Article"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "已经收藏，无需重复收藏"
// @router /article/collect/{id} [post]
func (c *ArticleController) ArticleCollect(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	article := model.Article2{}
	err = article.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	articleCollect := model.ArticleCollectE{}
	err = articleCollect.SelectByStudentIdArticleId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err == nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "已经收藏，无需重复收藏",
			Data:    "",
		}
	}
	articleCollect1 := model.ArticleCollect1{
		StudentId: uid,
		ArticleID: id,
	}
	err = articleCollect1.Insert()
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "收藏文章成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Article Like
// @Description 根据Id,添加到喜欢
// @Tags article
// @Param	id path int64	true "id for Article"
// @Param	body body response.TokenInfo	true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "已经喜欢，无需重复喜欢"
// @router /article/like/{id} [post]
func (c *ArticleController) ArticleLike(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	article := model.Article2{}
	err = article.SelectById(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	articleLike := model.ArticleLikeE{}
	err = articleLike.SelectByStudentIdArticleId(uid, id)
	if err != gorm.ErrRecordNotFound && err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err == nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "已经喜欢，无需重复喜欢",
			Data:    "",
		}
	}
	articleLike1 := model.ArticleLike1{
		StudentId: uid,
		ArticleId: id,
	}
	err = articleLike1.Insert()
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "喜欢文章成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Article UnCollect
// @Description 根据Id,去除收藏
// @Tags article
// @Param	id path int64	true "id for Article"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "没有收藏，无法去除收藏"
// @router /article/un_collect/{id} [post]
func (c *ArticleController) ArticleUnCollect(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	articleCollect := model.ArticleCollect0{}
	err = articleCollect.SelectByStudentIdArticleId(uid, id)
	if err != nil && err != gorm.ErrRecordNotFound {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err != nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "没有收藏，无法去除收藏",
			Data:    "",
		}
	}
	err = articleCollect.Delete(uid, id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Article UnLike
// @Description 根据Id,去除喜欢
// @Tags article
// @Param	id path int64	true "id for Article"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2	{string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @Failure 3 {string} string "没有喜欢，无法去除喜欢"
// @router /article/un_like/{id} [post]
func (c *ArticleController) ArticleUnLike(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	articleLike := model.ArticleLike0{}
	err = articleLike.SelectByStudentIdArticleId(uid, id)
	if err != nil && err != gorm.ErrRecordNotFound {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	} else if err != nil {
		return response.JsonResponse{
			ErrCode: 3,
			ErrInfo: "没有喜欢，无法去除喜欢",
			Data:    "",
		}
	}
	err = articleLike.Delete(uid, id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Article Collect List
// @Description 根据类别获取已收藏的知识视窗或者校园体育的文章列表
// @Tags article
// @Param	offset path int64	true "offset for list"
// @Param	type path int	true "type for article,0:知识视窗 1:校园体育"
// @Param	body body response.TokenInfo true "token"
// @Success 0	{object} response.ArticleList
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /article/collect/list/{type}/{offset} [post]
func (c *ArticleController) GetCollectArticleList(Type int, offset int) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	articleCollect := model.ArticleCollectE{}
	articleCollects, err := articleCollect.SelectAllByStudentId(uid)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	id := make([]int64, len(articleCollects))
	for i := 0; i < len(articleCollects); i++ {
		id[i] = articleCollects[i].ArticleID
	}
	article := model.ArticleE{}
	articles, err := article.SelectAllByIdType(id, byte(Type))
	res := response.ArticleList{
		ShortShowCount:  3,
		PerRequestCount: 8,
		TotalCount:      int64(len(articles)),
		Offset:          int64(offset),
		ArticleList:     []response.ArticleListInfo{},
	}
	for i := offset; i < offset+8 && i < len(articles); i++ {
		res.ArticleList = append(res.ArticleList, response.ArticleListInfo{
			Id:           articles[i].Id,
			Type:         int(Type),
			VideoPic:     articles[i].VideoPic,
			ThumbnailUrl: articles[i].ThumbnailUrl,
			VideoKey:     articles[i].VideoKey,
			WatchCount:   articles[i].WatchCount,
			LikeCount:    articles[i].LikeCount,
			Title:        articles[i].Title,
			CreateTime:   articles[i].CreateAt.Format("2006-01-02 15:04:05"),
			Description:  articles[i].Description,
		})
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}
